package stancel.peter.smslogger.activities;

import stancel.peter.smslogger.R;
import stancel.peter.smslogger.SMSLogger;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.Preference.OnPreferenceChangeListener;
import android.preference.Preference.OnPreferenceClickListener;

/**
 * Sluzi na menenie a ukladanie nastaveni pomocou preferencii.
 * @author Peter Stancel
 */
public class SettingsActivity extends PreferenceActivity implements
		OnPreferenceClickListener, OnPreferenceChangeListener {

	private SMSLogger smsLogger;
	
	/**
	 * Vola sa pri vytvarani tejto aktivity.
	 * Nastavuje listenery pre niektore preferencie.
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		addPreferencesFromResource(R.xml.preferences);

		smsLogger = (SMSLogger) getApplication();
		findPreference("smslogger_preferences_delete_sms").setOnPreferenceClickListener(this);
		findPreference("smslogger_preferences_set_notification").setOnPreferenceChangeListener(this);
	}

	/**
	 * Zavola sa ak sa klikne na preferenciu.
	 * <i>delete_sms</i> - vytvori dialog na potvrdenie operacie
	 */
	@Override
	public boolean onPreferenceClick(Preference preference) {
		new AlertDialog.Builder(this).setTitle(R.string.delete_sms).setMessage(
			R.string.delete_sms_message).setIcon(
			android.R.drawable.ic_dialog_alert).setPositiveButton(
			android.R.string.yes, new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int whichButton) {
					smsLogger.deleteAllSms();
				}
			}).setNegativeButton(android.R.string.no, null).show();
		return false;
	}

	/**
	 * Zavola sa, ak pouzivatel preferenciu zmeni.
	 * <i>set_notification</i> - pri zmene na false sa zmeni aj <i>set_mute</i> na false
	 */
	@Override
	public boolean onPreferenceChange(Preference preference, Object newValue) {
		if(newValue.equals(false)){
			findPreference("smslogger_preferences_set_mute").getEditor().putBoolean("smslogger_preferences_set_mute", false).commit();
		}
		return true;
	}
}